package com.esinhai.tz.util;

import com.esinhai.tz.common.Const;
import com.github.pagehelper.StringUtil;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

/**
 * Created by 32988 on 2018/4/13.
 */
public class ToolUtil {
    /**
     * @param o 操作对象
     * @param c 操作类，用于获取类中的方法
     * @return
     * @MethodName : getString
     * @Description : 获取类中所有属性及属性值
     */
    public static Map<String, Object> getString(Object o, Class<?> c) {
        Map<String, Object> map = new HashedMap();
        String result = c.getSimpleName() + ":";
        // 获取父类，判断是否为实体类
        if (c.getSuperclass().getName().indexOf("entity") >= 0) {
            result += "\n<" + getString(o, c.getSuperclass()) + ">,\n";
        }
        // 获取类中的所有定义字段
        Field[] fields = c.getDeclaredFields();
        // 循环遍历字段，获取字段对应的属性值
        for (Field field : fields) {
            // 如果不为空，设置可见性，然后返回
            field.setAccessible(true);
            try {
                // 设置字段可见，即可用get方法获取属性值。
                result += field.getName() + "=" + field.get(o) + ",\n";
                if (!StringUtil.isEmpty(field.get(o).toString())) {
                    map.put(field.getName(), field.get(o));
                }
            } catch (Exception e) {
                // System.out.println("error--------"+methodName+".Reason is:"+e.getMessage());
            }
        }
        //if(result.indexOf( "," )>=0) result = result.substring( 0 , result.length( )-2 );
        return map;
    }

    /**
     * 读取txt文件内容
     *
     * @param is
     * @return
     */
    public static String readToString(InputStream is) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String tempString = null;
            int line = 1;
            String josnString = "";
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                josnString += tempString;
                line++;
            }
            reader.close();
            return josnString;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return null;
    }

    public static String nowDate() {
        //得到long类型当前时间
        long l = System.currentTimeMillis();
        //new日期对象
        Date date = new Date(l);
        //转换提日期输出格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return dateFormat.format(date);
    }

    /**
     * 多文件传Base64方法 并合成一个String返回
     *
     * @param files
     * @return
     */
    public static String fileToStringUtile(MultipartFile[] files) {
        BASE64Encoder encoder = new BASE64Encoder();
        String datas = "";
        try {
            if (files != null && files.length > 0) {
                //循环获取file数组中得文件
                for (int i = 0; i < files.length; i++) {
                    MultipartFile file = files[i];
                    String filename = file.getOriginalFilename();
                    String data ="";
                    if (filename.contains("front")) {
                        data="front:"+ encoder.encode(file.getBytes());
                        datas = data + Const.SIGN + datas;
                    }else{
                        data=encoder.encode(file.getBytes());
                        datas = data + Const.SIGN + datas;
                    }

                    //ToolUtil.doFile(reloadProperties(Const.FILE_PATH), file, file.getName());
                    //保存文件
                }
            }
            return datas;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    /**
     * @param imgStr base64编码字符串
     * @param path   图片路径-具体到文件
     * @return
     * @Description: 将base64编码字符串转换为图片
     * @Author:
     * @CreateTime:
     */
    public synchronized static boolean generateImage(String imgStr, String path,String filename) {
        if (imgStr == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(imgStr);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            File file =new File(path);
            if  (!file .exists()  && !file .isDirectory()){
                file .mkdir();
            }
            OutputStream out = new FileOutputStream(path+filename);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        String u=Class.class.getClass().getResource("/").getPath();
        System.out.println(u);
    }
    /**
     * 上传文件
     *
     * @param path
     * @param daFile
     * @param fileName
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    public static String doFile(String path, MultipartFile daFile, String fileName) throws IllegalStateException, IOException {
        String filename = daFile.getOriginalFilename();
        String prefix = filename.substring(filename.lastIndexOf(".") + 1);
        String url = path + nowDate() + "\\" + fileName + prefix;
        File saveFileUrl = new File(url);
        if (!saveFileUrl.isDirectory()) {
            saveFileUrl.mkdirs();
        }
        daFile.transferTo(saveFileUrl);
        return url;
    }
    /**
     * 读取配置文件
     * @param key
     * @return
     */
    public static  String reloadProperties(String key) {
        Properties configuration = new Properties();
        InputStream is = ToolUtil.class.getClassLoader().getResourceAsStream("file.properties");
        try {
            configuration.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return configuration.getProperty(key);
    }
}